import {BEARER_PREFIX, TOKEN_NAME} from "@/util/constants.js";
import {confirm, showMessage} from "@/util/message.js";
import {ElMessage} from "element-plus";
import axios from "axios";
import qs from 'qs'

// 配置请求的根路径
axios.defaults.baseURL = 'http://localhost:1012';
/*const Dftaxios = axios.create({
    baseURL: 'http://localhost:1012',
    /!*timeout: 7000*!/
});*/
// 封装get请求
export const doGet = (url, params) => {
    return axios({
        url: url,
        method: 'get',
        params: params
    });
}
// 封装post请求
export const doPost = (url, data) => {

    return axios({
        url: url,
        method: 'post',
        data: data
    });
}
// 封装put请求
export const doPut = (url, data) => {
    return axios({
        url: url,
        method: 'put',
        data: data
    });
}
// 封装delete请求
export const doDelete = (url, data) => {
    return axios({
        url: url,
        method: 'delete',
        data: data
    });
}
// 封装下载请求
export const doDownload = (url, params) => {
    return axios({
        method: 'get',
        url: url,
        params: params,
        responseType: 'blob'
    });
}
export const doForm = (url, params) => {
    return axios({
        url: url,
        method: 'post',
        data: qs.stringify(params),
    })
}

// 添加请求拦截器
axios.interceptors.request.use((request) => {
    let sessionJson = sessionStorage.getItem(TOKEN_NAME);
    if (sessionJson) {
        let session = JSON.parse(sessionJson);
        request.headers.Authorization = BEARER_PREFIX + session.jwt
        request.headers.loginId = session.loginId;
    }
    return request;
})

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 判断响应状态码是否为204，如果是则删除token并跳转到登录页面
    if (response.data.code > 900) {
        confirm('登录过期，请重新登录').then(() => {
            //删除token
            localStorage.removeItem(TOKEN_NAME);
            //删除会话存储中的token
            sessionStorage.removeItem(TOKEN_NAME);
            window.location.href = '/';
        })
        //跳转到登录页面
    }
    return response;
}, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
});
